// 请从课程简介里下载本代码
import React, { useState, useContext, useEffect } from 'react'
import { Connect, Provider } from '../store'
import store from '../store/initStore'

export default () => {
  return (
    <Provider store={store}>
      <Box0Wrapper />
      <Box />
      <Box0Wrapper3 />
    </Provider>
  )
}

const Box0 = ({ name }) => {
  console.log('state ===> ', name)
  return <div>{name}</div>
}

const Box = () => (
  <>
    edit
    <Wrapper2 />
  </>
)

const Box1 = ({ group }) => <>{group}</>

const UserModifier = ({ updateName, name, dispatch }) => {
  const onChange = (e) => {
    updateName({ name: e.target.value })
  }
  // 异步action
  const fetchUser = () => {
    setTimeout(() => {
      // 异步结束后 调用同步修改
      updateName({ name: '三秒后的NAME' })
    }, 5000)
  }

  // 异步 action.payload
  const fetchUserPromise = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({ name: 'resolve过去了三秒' })
      }, 3000)
    })
  }

  return (
    <div>
      <input value={name} onChange={onChange} />
      <button
        onClick={() => {
          // 异步结束以后调用dispatch修改name
          // redux 不支持动态使用reducer修改state 所以需要中间件进行处理
          // setTimeout(() => {
          //   updateName({ name: "三秒后的NAME" });
          // }, 3000);

          // 支持异步aaction
          // dispatch(fetchUser());

          // 支持异步action.payload  (请勿同时取消注释 源码存在重写逻辑)
          updateName(fetchUserPromise())
        }}
      >
        异步修改name
      </button>
    </div>
  )
}

const mapStateToProps = function (state) {
  return {
    name: state.user.name,
  }
}

const mapDispatchToProps = function (dispatch) {
  return {
    updateName: (payload) => dispatch({ type: 'updateUser', payload }),
    dispatch,
  }
}

const mapStateToProps3 = function (state) {
  return {
    group: state.group,
  }
}

// 如果maoStateToProps了 那么组件只会讲所使用的变量发生变化时 进行更改
const Wrapper2 = Connect(mapStateToProps, mapDispatchToProps)(UserModifier)
const Box0Wrapper = Connect(mapStateToProps)(Box0)
const Box0Wrapper3 = Connect(mapStateToProps3)(Box1)
